#include "ad_oneclassinfo.h"
#include "ui_ad_oneclassinfo.h"

#include "mytablevive.h"

#include <QListView>
#include <QTimer>

AD_OneClassInfo::AD_OneClassInfo(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AD_OneClassInfo)
{
    ui->setupUi(this);

    TOOLS->setTableHead(ui->tableWidget,{"姓名"});
    TOOLS->setTableHead(ui->tableWidget_2,{"课程","教师"});

    ui->tableWidget->setEditTriggers(QAbstractItemView::AllEditTriggers);
    for(auto child : this->children()){
        auto combo = qobject_cast<QComboBox*>(child);
        if(combo){
            combo->setView(new QListView);
        }
    }


}

AD_OneClassInfo::~AD_OneClassInfo()
{
    delete ui;
}

void AD_OneClassInfo::setMode(const QString &mode)
{
    m_mode = mode;

    bool add = false;

    if(m_mode.contains("add")){
         add = true;
    }else if(m_mode.contains("update")){
        add = false;
        if(ui->comboBoxClassView->count() > 0){
            on_comboBoxClassView_activated(0);

        }
    }

    if(m_mode.contains("consultant")){
        ui->pushButton->show();
        ui->comboBoxCounselor->hide();
        ui->label_3->hide();

        auto res = DB->getAllStudentInfo(QString("consultantID = %1").arg(GDATA->Account));

        TOOLS->showEarlyWarning(res,"这些学生学情状况不好，请及时关注！");


    }else{
        ui->label_3->show();
        ui->comboBoxCounselor->show();
        ui->pushButton->hide();
    }

    updateForAdd();

    ui->comboBoxClassView->setVisible(!add);
    ui->add->setVisible(add);
    ui->pushButtonUpdate->setVisible(!add);
    ui->pushButtonOK->setVisible(add);
}

void AD_OneClassInfo::setClassListComboBox(QString where)
{
    QString tableName = "classes";
    auto classList =  DB->getTableInfo(tableName,where);
    if(classList.isEmpty()){
        LOG("查询班级失败");
        return;
    }

    ui->comboBoxClassView->clear();
    for(auto aClass : classList){
        QSignalBlocker blocker(ui->comboBoxClassView);

        ui->comboBoxClassView->addItem(aClass.at(2).toString(),aClass.at(0).toInt());
    }

    QTimer::singleShot(200,[=](){
        setTableDataFromClassId(classList.at(0).at(0).toInt());
    });
}

void AD_OneClassInfo::setStudentTableFormClassId(int id)
{

}

void AD_OneClassInfo::setCoursesTableFormClassId(int id)
{

}

int AD_OneClassInfo::getClassId()
{
    if(m_mode.contains("update")){
        return ui->comboBoxClassView->currentData().toInt();
    }

    int yuar = ui->spinBox->value();
    int pr = ui->comboBoxProfessional->currentData().toInt();
    int index = ui->comboBoxClass->currentIndex()+1;

    int id = index + pr * 100 +  yuar * 10000;

    qDebug()<< id;

    return id;
}

int AD_OneClassInfo::getCounID()
{
    return ui->comboBoxCounselor->currentData().toInt();
}

QString AD_OneClassInfo::getClassName()
{
    int yuar = ui->spinBox->value();
    QString pr = ui->comboBoxProfessional->currentText();
    int index = ui->comboBoxClass->currentIndex()+1;

    QString rData = "%1(%2级%3班)";
    return rData.arg(pr).arg(yuar).arg(index);
}

void AD_OneClassInfo::updateForAdd()
{
    // 专业数据
    // 教师数据
    // 课程数据
    // 辅导员数据
    m_allCreateInfo = DB->getCreateClassInfo();


    setCombo(ui->comboBoxCounselor,m_allCreateInfo.counselors);

    if(m_mode.contains("update")){
        return;
    }

    setCombo(ui->comboBoxProfessional,m_allCreateInfo.professionals);


}

QStringList AD_OneClassInfo::getStudents()
{
    QStringList rData;
    auto table = ui->tableWidget;
    for (int row = 0; row < table->model()->rowCount(); row++ ) {
        rData << table->item(row,0)->text();
    }

    return rData;

}

void AD_OneClassInfo::setCombo(QComboBox *combo, QList<DB_CreateClassInfo::T_Info> data)
{
    combo->clear();
    for(auto && item:data){
        combo->addItem(item.name,item.id);
    }
}

void AD_OneClassInfo::setTableDataFromClassId(int classID)
{
    // consultant
    auto classdata = DB->getTableInfo("classes",QString("class_id = %1").arg(classID));
    auto consultant_id = classdata.at(0).at(1).toInt();
    auto index = ui->comboBoxCounselor->findData(consultant_id);
    ui->comboBoxCounselor->setCurrentIndex( index);


    // student
    auto t1 = ui->tableWidget;
    auto data = DB->getTableInfo("userInfo",QString("class_id = %1").arg(classID));

    t1->setRowCount(data.count());
    for(int i = 0 ; i < data.count() ; i++){
        t1->setItem(i,0,new QTableWidgetItem(data.at(i).at(1).toString()));
    }

    // courses
    auto t2 = ui->tableWidget_2;
    auto cData = DB->getAllClassInfo(QString("classID = %1").arg(classID));

    t2->setRowCount(cData.count());
    for(int row = 0; row < cData.count();row++){
        auto aRow = cData.at(row);

        auto cour = getCoursesComboBox();
        cour->setCurrentText(aRow.courseName);
        auto teac = getTeachersComboBox();
        teac->setCurrentText(aRow.TName);

        t2->setCellWidget(row,0,cour);
        t2->setCellWidget(row,1,teac);

    }
}

QComboBox *AD_OneClassInfo::getCoursesComboBox()
{
    auto item = new QComboBox();
    auto&& items = m_allCreateInfo.courses;

    item->setView(new QListView);
    setCombo(item,items);

    return item;

}

QComboBox *AD_OneClassInfo::getTeachersComboBox()
{
    auto item = new QComboBox();
    auto&& items = m_allCreateInfo.teachers;

    item->setView(new QListView);
    setCombo(item,items);

    return item;
}

bool AD_OneClassInfo::classCreate(QSqlQuery *qu)
{
    QString tableName = "classes";
    auto classID = getClassId();
    auto oldClass = DB->getTableInfo(tableName,QString("class_id = %1").arg(classID));
    if(oldClass.isEmpty() == false){
        LOG("已经创建该班级");
        return false;
    }


    int id,counId;
    QString name;

    id = getClassId();
    counId = getCounID();
    name = getClassName();

    QVariantList data = {id,counId,name};

    DB->insertTableInfo(tableName,QList<QVariantList>()<<data,qu);


    return true;
}

bool AD_OneClassInfo::enrollmentCreate(QSqlQuery *qu)
{
    QString tableName = "enrollments";
    int proId = getClassId();


    QList<QVariantList> data;
    for (int i =0;i<ui->tableWidget_2->rowCount() ;i++ ) {
        QVariantList aRow;
        aRow << proId;
        aRow << qobject_cast<QComboBox*>(ui->tableWidget_2->cellWidget(i,0))->currentData().toInt();
        aRow << qobject_cast<QComboBox*>(ui->tableWidget_2->cellWidget(i,1))->currentData().toInt();
        data << aRow;
    }

    DB->insertTableInfo(tableName,data,qu);


    return true;
}

bool AD_OneClassInfo::studentsCreate(QSqlQuery *qu)
{
    QString tableName = "userInfo";
    int proId = getClassId();

    auto names = getStudents();

    QList<QVariantList> data;
    for (int i =0;i<names.count() ;i++ ) {
        QVariantList aRow;
        aRow << proId*100+ i+1;
        aRow <<names.at(i) << "123456" << 0 << 0 << 0 << 1 << proId;
        data << aRow;
    }

    DB->insertTableInfo(tableName,data,qu);


    return true;

}

bool AD_OneClassInfo::enrollmentDelete(QSqlQuery *qu)
{
    QString tableName = "enrollments";
    int proId = getClassId();

    DB->deleteTableInfo(tableName,QString("class_id = %1").arg(proId),qu);

    return true;
}

bool AD_OneClassInfo::studentsDelete(QSqlQuery *qu)
{
    QString tableName = "userInfo";
    int proId = getClassId();

    DB->deleteTableInfo(tableName,QString("class_id = %1").arg(proId),qu);

    return true;
}

bool AD_OneClassInfo::updateClassConsultantID(QSqlQuery *qu)
{



    QString tableName = "classes";
    QString set = QString("consultant_id = %1").arg(getCounID());
    QString where = QString("class_id = %1").arg(getClassId());

    DB->updateTableInfo(tableName,set,where,qu);

    return true;
}

void AD_OneClassInfo::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    m_allCreateInfo = DB->getCreateClassInfo();
}

void AD_OneClassInfo::on_pushButtonAddCourse_clicked()
{

    auto table = ui->tableWidget_2;

    int curRow = table->rowCount();
    table->setRowCount(curRow+1);
    table->setCellWidget(curRow,0,getCoursesComboBox());
    table->setCellWidget(curRow,1,getTeachersComboBox());
}


void AD_OneClassInfo::on_pushButtonDeleteCourse_clicked()
{
    auto table = ui->tableWidget_2;

    int curRow = table->currentRow();
    if(curRow < 0){
        return ;
    }

    table->removeRow(curRow);
}


void AD_OneClassInfo::on_pushButtonAddStudent_clicked()
{
    auto table = ui->tableWidget;

    int curRow = table->rowCount();
    table->setRowCount(curRow+1);


    table->setItem(curRow,0,new QTableWidgetItem("姓名"));
}


void AD_OneClassInfo::on_pushButtonDeleteStudent_clicked()
{
    auto table = ui->tableWidget;

    int curRow = table->currentRow();
    if(curRow < 0){
        return ;
    }

    table->removeRow(curRow);
}



void AD_OneClassInfo::on_pushButtonOK_clicked()
{
    //添加班级
    //添加学生
    //添加课程关联表

    QSqlQuery u;
    u.exec("begin;");

    classCreate(&u);

    studentsCreate(&u);

    enrollmentCreate(&u);

    if (u.exec("commit;")){
        LOG("成功");
        PAGEJUMP->setPage(DK_AD_ClassMgrList);

    }else{
        LOG("失败");
        u.exec("rollback;");
    }
}




void AD_OneClassInfo::on_pushButton_3_clicked()
{
    CSV->tabelLoadFile(ui->tableWidget,TOOLS->openCSVOpenDialog());
}


void AD_OneClassInfo::on_pushButton_7_clicked()
{
    CSV->tabelSaveFile(ui->tableWidget,TOOLS->openCSVSaveDialog());
}


void AD_OneClassInfo::on_pushButtonOK_2_clicked()
{
    PAGEJUMP->setPage(DK_AD_ClassMgrList);
}


void AD_OneClassInfo::on_pushButtonUpdate_clicked()
{
    {

        QSqlQuery u;
        u.exec("begin;");

        studentsDelete(&u);

        enrollmentDelete(&u);

        u.exec("commit;");
    }

    {

        QSqlQuery u;

        u.exec("begin;");

        updateClassConsultantID(&u);

        studentsCreate(&u);

        enrollmentCreate(&u);

        if (u.exec("commit;")){
            LOG("成功");
            if(m_mode.contains("consultant")){
                return;
            }

            PAGEJUMP->setPage(DK_AD_ClassMgrList);
        }else{
            LOG("失败");
            u.exec("rollback;");
        }

    }
}


void AD_OneClassInfo::on_comboBoxClassView_activated(int index)
{
    Q_UNUSED(index)
    int classId = ui->comboBoxClassView->itemData(index).toInt();

    setTableDataFromClassId(classId);

}


void AD_OneClassInfo::on_pushButton_clicked()
{


    QSqlQueryModel* mo = new QSqlQueryModel;
    QString sql = R"(SELECT *  FROM %1 WHERE %2)";
    sql = sql.arg("studentGrades").arg(QString("classID = %1").arg(getClassId()));
    mo->setQuery(sql);
    auto ro = mo->rowCount();

    QStringList head = QString("学号,姓名,班级ID,课程ID,课程,学分,成绩,绩点,班级排名")
            .split(",");

    for (int i = 0 ; i < head.count() ;i++ ) {
        mo->setHeaderData(i,Qt::Horizontal,head[i]);
    }

//    auto wid = new QWidget(this);

//    QTableView* vi = new QTableView(wid);
//    vi->setModel(mo);

//    auto lay = new QHBoxLayout(wid);
//    lay->addWidget(vi);

//    wid->setLayout(lay);

//    wid->show();
//    wid->resize(1000,800);

    auto wid = new MyTableVive;
    wid->show();
    wid->getView()->setModel(mo);


    connect(wid,&MyTableVive::sg_close,[=](){
        CSV->tabelSaveFile(mo,TOOLS->openCSVSaveDialog());

    });


    //CSV->tabelSaveFile(mo,TOOLS->openCSVSaveDialog());


}

